module main

import vweb
import markdown
import os
import flag
import net {AddrFamily}

struct App {
	vweb.Context
	web_path shared Path
}

struct Path {
	s string
}

fn main() {
	mut fp := flag.new_flag_parser(os.args)
    fp.application('mdreader')
    fp.version('v0.0.1')
    fp.limit_free_args(0, 0)?
    fp.description('view markdown via browser, designed by buyi @2022.')
    fp.skip_executable()

    host := fp.string('host', 'H'[0], 'localhost', 'host ip, default localhost')
    port := fp.int('port', 'p'[0], 3000, 'server port, default 3000')
    ip6 := fp.bool('ip6', '6'[0], false, 'IPv6')
    markdown_path := fp.string('path', 0, '.', 'markdown directory, not yet support multi level directory')
    // daemon := fp.bool('daemon', 0x68, false, 'backgroud running')
    help := fp.bool('help', 'h'[0], false, 'This Help')

    if help {
    	// println(fp.usage())
    	println(usage(fp))
    	return
	}

	fp.finalize() or {
        eprintln(err)
        return
    }

	mut app := App{
		web_path: Path{markdown_path}
	}
	// lock app.web_path { app.web_path.s = markdown_path }
	family := if ip6 { AddrFamily.ip6 } else { AddrFamily.ip }
	param := vweb.RunParams{
		host: host
		port: port
		family: family
	}
	vweb.run_at(app, param) or {
		panic(err)
	}
}

['/']
pub fn (mut app App) index() vweb.Result {
	return app.text(app.ip())
}

['/reader/:f']
pub fn (mut app App) reader(f string) vweb.Result {
	web_path := rlock app.web_path { app.web_path.s }
	text := os.read_file('${web_path}/${f}.md') or { 
		return vweb.not_found()
	}
	body := vweb.RawHtml(markdown.to_html(text))
	return $vweb.html()
}
